package org.iks.user.web.controller;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.iks.common.AjaxResult;
import org.iks.common.ResultCode;
import org.iks.common.exception.BusinessException;
import org.iks.common.util.HashUtil;
import org.iks.common.util.JwtUtil;
import org.iks.common.util.ServletUtil;
import org.iks.user.util.SMUtil;
import org.iks.user.web.entity.UserEntity;
import org.iks.user.web.service.UserService;
import org.iks.user.web.vo.UserInfoVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author kzou
 * @date 2023/12/30 11:08
 * @description:
 */
@Tag(name = "用户模块")
@Slf4j
@RestController
public class UserController {
    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;

    public UserController(UserService userService, RedisTemplate<String, Object> redisTemplate) {
        this.userService = userService;
        this.redisTemplate = redisTemplate;
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/query/info")
    public AjaxResult<UserInfoVo> queryUserInfo(@RequestParam(required = false) String account) {
        if (account == null) {
            account = ServletUtil.currUser().account();
            if (account == null) {
                return AjaxResult.error(ResultCode.LOGIN_OFFLINE);
            }
        }
        UserEntity userEntity = userService.queryUserByAccount(account);
        if (userEntity == null) {
            return AjaxResult.error(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        UserInfoVo data = UserInfoVo.valueOf(userEntity);
        return AjaxResult.success(data);
    }

    @Operation(summary = "获取用户信息[批量]")
    @PostMapping("/query/info/batch")
    public AjaxResult<List<UserInfoVo>> queryUserInfoBatch(@RequestBody Set<String> accounts) {
        List<UserInfoVo> userInfoVos = new ArrayList<>();
        for (String account : accounts) {
            UserEntity userEntity = userService.queryUserByAccount(account);
            UserInfoVo data = UserInfoVo.valueOf(userEntity);
            userInfoVos.add(data);
        }
        return AjaxResult.success(userInfoVos);
    }

    /**
     * 用户搜索
     *
     * @param account 账号或用户名称
     */
    @Operation(summary = "用户搜索")
    @PostMapping("/search")
    public AjaxResult<List<UserInfoVo>> simpleSearch(String account) {
        List<UserInfoVo> users = userService.simpleSearch(account);
        return AjaxResult.success(users);
    }

    @Operation(summary = "获取登录令牌")
    @PostMapping("/login/token")
    public AjaxResult<?> registerToken(@RequestParam("publicKey") String hexPublicKey) throws Exception {
        String registerToken = RandomUtil.randomString(6);
        String token = SMUtil.encryptHex(hexPublicKey, registerToken);
        redisTemplate.opsForValue().set(HashUtil.md5(hexPublicKey), registerToken, Duration.ofMinutes(3));
        return AjaxResult.success(token);
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AjaxResult<?> userRegister(String hexPublicKey, String signToken) throws Exception {
        String res = (String) redisTemplate.opsForValue().get(HashUtil.md5(hexPublicKey));
        if (res == null) {
            throw new BusinessException(ResultCode.USER_LOGIN_ERROR);
        }
        res = HexUtil.encodeHexStr(res);
        boolean validRes = SMUtil.isValid(hexPublicKey, res, signToken);
        if (!validRes) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_PASSWORD_ERROR);
        }
        UserEntity userEntity = userService.userLogin(hexPublicKey);
        // 创建用户令牌
        String token = JwtUtil.createToken(userEntity.getAccount(), hexPublicKey);
        return AjaxResult.success(token);
    }



}
